package anatex.web;

import java.io.OutputStream;


import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import anatex.domain.Task;
import anatex.domain.TaskLog;
import java.util.List;

@Controller
public class ChartController {
 
  @RequestMapping("/task-log-chart.png")
  public void renderChart(@RequestParam("task") Task t, OutputStream stream) throws Exception {
    JFreeChart chart = generateChart(t);
    ChartUtilities.writeChartAsPNG(stream, chart, 500, 300);
  }
 
  private JFreeChart generateChart(Task t){
    XYDataset data = getDataset(t);
    
    return ChartFactory.createXYLineChart(
        "Genex development in time",      // chart title
        "Iteration",                      // x axis label
        "Population Fitness",       	// y axis label
        data,                  // data
        PlotOrientation.VERTICAL,
        true,                     // include legend
        true,                     // tooltips
        false                     // urls
    );
  }

  private XYDataset getDataset(Task t){
      // Run the SQL query and add the results to the JFreeChart dataset

	  XYSeries series1 = new XYSeries("GenEx");
	  
	  try {
		  List<TaskLog> tLogs = TaskLog.findTaskLogsByTask(t).getResultList();
		  
		  for (TaskLog tl : tLogs) {
			  series1.add(new Double(tl.getIteration()), tl.getAverageFitness());
		  }
		  
	  } catch (Exception ex) {
		  System.out.println("Error occured during collecting task logs for task...");
		  ex.printStackTrace(System.out);
	  }
      
      XYSeriesCollection dataset = new XYSeriesCollection();
      dataset.addSeries(series1);
      
      return dataset;
  }
 
}